/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.integral.web.controller.api;

import com.medusa.gruul.common.core.annotation.EscapeLogin;
import com.medusa.gruul.common.core.exception.ServiceException;
import com.medusa.gruul.common.core.util.CurUserUtil;
import com.medusa.gruul.common.core.util.Result;
import com.medusa.gruul.common.core.util.StringUtil;
import com.medusa.gruul.common.core.util.SystemCode;
import com.medusa.gruul.common.dto.CurUserDto;
import com.medusa.gruul.integral.service.IIntegralEnterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 * 积分登入表 前端控制器
 * </p>
 *
 * @author xiaoq
 * @since 2019-12-31
 */

@RestController
@RequestMapping("enter")
@Api(tags = "用户登入相关接口")
public class ApiIntegralLogInController {

    @Autowired
    private IIntegralEnterService integralEnterService;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 用户进行登入 修改登入状态并生成积分明细记录
     *
     * @return 用户登入获得的积分
     */
    @ApiOperation(value = "用户登入,获取积分")
    @PostMapping("updateStatus")
    @EscapeLogin
    public Result updateRunningDays() {
        CurUserDto feignCurUser = CurUserUtil.getHttpCurUser();
        if (feignCurUser == null) {
            throw new ServiceException("数据错误", SystemCode.DATA_NOT_EXIST.getCode());
        }
        String userId = feignCurUser.getUserId();
        // 增加分布式锁
        RLock rLock = redissonClient.getLock(userId);
        rLock.lock();
        BigDecimal bigDecimal = BigDecimal.ZERO;
        try {
            bigDecimal = integralEnterService.userLogin(userId);
        } finally {
            //释放锁
            rLock.unlock();
        }
        return Result.ok(bigDecimal);
    }
}
